<template>
  <ContentWrap title="主数据">
    <el-form
      ref="ruleFormRef"
      :rules="rules"
      :model="ff"
      label-position="top"
      :inline="false"
      class="demo-form-inline"
    >
      <el-form-item label="所属牧场" prop="pasture_org_name">
        <ElInput
          @click="action('edit')"
          v-model="ff.pasture_org_name"
          placeholder="点击选择"
          v-bind="$attrs"
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="所属部门" prop="pasture_dept_name">
        <!-- <el-select v-model="ff.pasture_dept_name">
          <el-option
            v-for="data in dept"
            :key="data.dept_id"
            :label="data.dept_name"
            :value="data.dept_id"
          />
        </el-select> -->

        <el-tree-select
          v-model="ff.pasture_dept_name"
          :data="dept"
          check-strictly
          :render-after-expand="false"
          :props="{ value: 'dept_id', label: 'dept_name' }"
          :default-expand-all="true"
          :highlight-current="true"
        />
      </el-form-item>

      <el-form-item label="盘点规则名称" prop="name">
        <el-input
          style="width: 200px"
          v-model="ff.name"
          :placeholder="`请输入相应的${props.detailSchema[1].label}`"
          :clearable="true"
        />
      </el-form-item>

      <el-form-item label="盘点类型" prop="type">
        <el-select v-model="ff.type">
          <el-option
            v-for="data1 in formInline"
            :key="data1.value"
            :label="data1.label"
            :value="data1.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="note">
        <el-input style="width: 200px" v-model="ff.note" placeholder="备注" :clearable="true" />
      </el-form-item>
    </el-form>
    <div v-if="ff.type == '2'">
      <hr />
      <br />
      <Search
        :schema="allSchemas.searchSchema"
        @search="setSearchParamss"
        @reset="setSearchParamss"
      />

      <TableAsset
        v-model:pageSize="tableObjects.pageSize"
        v-model:currentPage="tableObjects.currentPage"
        v-model:checkedAll="checkedAll"
        v-model:noSelectData="noSelectData"
        v-model:selectData="selectData"
        :columns="allSchemas.tableColumns"
        :data="tableObjects.tableList"
        :loading="tableObjects.loading"
        :border="true"
        :pagination="{
          total: tableObjects.count
        }"
        @register="registers"
        :row-key="getRowKey"
        :selection="true"
        highlight-current-row
      />
    </div>
    <div v-if="ff.type == '3'">
      <ElTree
        ref="treeRef"
        :data="listData1"
        :props="defaultProps"
        node-key="id"
        @check="currentChecked"
        show-checkbox
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node }">
          <span class="custom-tree-node">
            <span
              >{{ t(node.label) }}
              <ElTag
                :type="
                  node.data.type == '1' ? 'success' : node.data.type == '2' ? 'warning' : 'danger'
                "
              >
                {{ node.data.type == '1' ? '育肥' : node.data.type == '2' ? '低效' : '' }}
              </ElTag>
            </span>
          </span>
        </template>
      </ElTree>
    </div>
    <div v-if="ff.type == '4'">
      <hr />
      <br />
      <Search
        :schema="allSchemas.searchSchema"
        @search="setSearchParamss"
        @reset="setSearchParamss" />

      <TableAsset
        v-model:pageSize="tableObjects.pageSize"
        v-model:currentPage="tableObjects.currentPage"
        v-model:checkedAll="checkedAll"
        v-model:noSelectData="noSelectData"
        v-model:selectData="selectData"
        :columns="allSchemas.tableColumns"
        :data="tableObjects.tableList"
        :loading="tableObjects.loading"
        :border="true"
        :pagination="{
          total: tableObjects.count
        }"
        @register="registers"
        :row-key="getRowKey"
        :selection="true"
        highlight-current-row
    /></div>
    <div v-if="ff.type == '5'">
      <hr />
      <br />
      <Search
        :schema="allSchemas.searchSchema"
        @search="setSearchParamss"
        @reset="setSearchParamss" />
      <TableAsset
        v-model:pageSize="tableObjects.pageSize"
        v-model:currentPage="tableObjects.currentPage"
        v-model:checkedAll="checkedAll"
        v-model:noSelectData="noSelectData"
        v-model:selectData="selectData"
        :columns="allSchemas.tableColumns"
        :data="tableObjects.tableList"
        :loading="tableObjects.loading"
        :border="true"
        :pagination="{
          total: tableObjects.count
        }"
        @register="registers"
        :row-key="getRowKey"
        :selection="true"
        highlight-current-row
    /></div>
    <Dialog v-model="dialogVisible" title="双击选择">
      <Mu ref="editRef" />
      <template #footer>
        <ElButton @click="save()"> 保存 </ElButton>
        <!-- <ElButton v-if="actionType !== 'see'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton> -->
        <ElButton @click="dialogVisible = false">关闭</ElButton>
      </template>
    </Dialog>
  </ContentWrap>
</template>

<script setup lang="ts">
import { zcAssetListApi } from '@/api/cy/xPanrule'
import { PropType, reactive, ref, unref, watch } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useTable } from '@/hooks/web/useTableTest'
import { useI18n } from '@/hooks/web/useI18n'
const { t } = useI18n()
import { spEnclosureListApi } from '@/api/fa/enclosure'
import { required } from '@/utils/formRules'
import { FormInstance, FormRules } from 'element-plus'
import { TableAsset } from '@/components/TableSelect'

import Mu from '@/views/AAA/Mu.vue'
import { ElForm, ElFormItem, ElInput } from 'element-plus'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
import { sysDictRelsApi } from '@/api/dict'
import { zcInventoryRuleSeeApi } from '@/api/cy/xPanrule'
import { ucDeptListApi } from '@/api/uc/dept'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}
// form验证ref
const ruleFormRef = ref<FormInstance>()

const treeRef = ref()

const dictRelsData = ref() // 联动数据
const searchRef = ref() // 搜索的标签
const breedSubData: any = ref([]) // 品种的枚举

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

const actionType = ref('')

const action = async (type: string) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}

const editRef = ref()

const save = async () => {
  const edit: any = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      console.log(edit)
      // dialogVisible.value = false
      ff.value.pasture_org_name = edit.aaa.org_name
      ff.value.pasture_org_id = edit.aaa.org_id
      dialogVisible.value = false
      break
    default:
      console.log('未知类型')
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

// 选择畜别的时候触发，处理品种类容
const breedChange = (value) => {
  breedGetSub(value)
  const new_search = unref(searchRef)
  new_search.setData({ ...new_search.getData(), breed_sub: '' })
}

const getRowKey = (row) => {
  return row.id
}
const rules = reactive<FormRules>({
  type: [required],
  name: [required],
  address: [required],
  pasture_org_name: [required],
  pasture_dept_name: [required]
})

const dialogVisible = ref(false)
// // 自定义按钮
// const fff = (row) => {
//   console.log(row, '1234')
//   dialogVisible.value = false
//   ff.value.pasture_org_name = row.org_name
//   ff.value.pasture_org_id = row.org_id
// }
const defaultProps = {
  children: 'children',
  label: 'name'
}
// 结束后填写的信息
let ff = ref<any>({
  name: '',
  type: '',
  note: '',
  selected: [],
  pasture_org_id: '',
  pasture_org_name: '',
  pasture_dept_name: '',
  pasture_dept_id: ''
})
const typeOne = ref('')
// 栏位列表数据
let listData1 = ref([])

let methodss: any = ref()
let tableObjects = ref()
let registers = ref()
let setSearchParamss = ref()
let getLists = ref()
const elTableRefs = ref()
const newFixedSearch = ref({})
// can: { select_type: a, pasture_org_id: ff.value.name_id }

const getListAsset = async () => {
  tableObjects.value.tableList = []
  console.log(ff.value, 'date')
  if (ff.value.pasture_org_id) {
    let res = reactive<any>([])
    if (ff.value.type == 2) {
      const re = await zcAssetListApi({
        is_die: '0',
        my_org_id: wsCache.get('userInfo').default_org_id,
        pasture_org_id: ff.value.pasture_org_id,
        pageSize: tableObjects.value.pageSize,
        pageNo: tableObjects.value.currentPage,
        // breed: ff.value.breed,
        // breed_sub: ff.value.breed_sub,
        earcon_code: tableObjects.value.paramsObj.params
          ? tableObjects.value.paramsObj.params.earcon_code
          : null,
        asset_code: tableObjects.value.paramsObj.params
          ? tableObjects.value.paramsObj.params.asset_code
          : null
      })
        .catch(() => {})
        .finally(() => {})
      res = re
      console.log(re)
    } else if (ff.value.type == 4) {
      const re = await zcAssetListApi({
        loan_state: 3,
        is_die: '0',
        my_org_id: wsCache.get('userInfo').default_org_id,
        pasture_org_id: ff.value.pasture_org_id,
        pageSize: tableObjects.value.pageSize,
        pageNo: tableObjects.value.currentPage,
        // breed: ff.value.breed,
        // breed_sub: ff.value.breed_sub,
        earcon_code: tableObjects.value.paramsObj.params
          ? tableObjects.value.paramsObj.params.earcon_code
          : null,
        asset_code: tableObjects.value.paramsObj.params
          ? tableObjects.value.paramsObj.params.asset_code
          : null
      })
        .catch(() => {})
        .finally(() => {})
      res = re
      console.log(re)
    } else if (ff.value.type == 5) {
      const re = await zcAssetListApi({
        is_insure: 1,
        is_die: '0',
        my_org_id: wsCache.get('userInfo').default_org_id,
        pasture_org_id: ff.value.pasture_org_id,
        pageSize: tableObjects.value.pageSize,
        pageNo: tableObjects.value.currentPage,
        // breed: ff.value.breed,
        // breed_sub: ff.value.breed_sub,
        earcon_code: tableObjects.value.paramsObj.params
          ? tableObjects.value.paramsObj.params.earcon_code
          : null,
        asset_code: tableObjects.value.paramsObj.params
          ? tableObjects.value.paramsObj.params.asset_code
          : null
      })
        .catch(() => {})
        .finally(() => {})
      res = re
      console.log(re)
    }

    if (res) {
      tableObjects.value.tableList = res.data
      tableObjects.value.count = res.count
      tableObjects.value.loading = false
    }
  }
}

watch(
  () => ff.value.type,
  async (a) => {
    if (a == '3') {
      await spEnclosureListApi({
        org_id: ff.value.pasture_org_id
      }).then(
        function (value) {
          // 异步操作执行成功后的处理
          console.log(value.data, 'value.data')
          listData1.value = value.data
          if (props.id) {
            if (typeOne.value == '3' && typeOne.value == ff.value.type) {
              setTimeout(() => {
                treeRef.value!.setCheckedKeys(ff.value.ids.split(','))
              }, 0)
              console.log(typeOne.value)
            }
          }
        },
        function (error) {
          // 异步操作失败的处理
          console.log(error)
        }
      )
    } else if (a == 2 || a == 4 || a == 5) {
      // 资产
      const { register, tableObject, methods, elTableRef } = useTable<
        {
          total: number
          list: any[]
        },
        any
      >({
        getListApi: getListAsset,
        response: {
          data: 'data',
          count: 'count'
        }
      })
      const { getList, setSearchParams } = methods

      methodss.value = methods
      elTableRefs.value = elTableRef
      tableObjects.value = tableObject
      registers.value = register
      getLists.value = getList
      setSearchParamss.value = setSearchParams
      newFixedSearch.value = {
        pasture_org_id: ff.value.pasture_org_id,
        select_type: a
      }
      tableObjects.value.fixedSearch = newFixedSearch.value
      // if (!props.id) {
      getList()
      // }

      const Gou = async () => {
        if (typeOne.value != '3' && typeOne.value == ff.value.type) {
          if (checkedAll.value) {
            await getList()
            if (noSelectData.value.length > 0) {
              // 去重
              let newArr = tableObject.tableList.filter(
                (x) => !noSelectData.value.some((item) => x.id == item.id)
              )
              newArr.forEach((row) => {
                elTableRef.value.toggleRowSelection(row, true)
              })
            } else {
              tableObject.tableList.forEach((row) => {
                elTableRef.value.toggleRowSelection(row, true)
              })
            }
          } else {
            getList()
            // num.value = selectData ? props.selectData.length : 0
            setTimeout(() => {
              if (selectData.value && selectData.value.length > 0) {
                selectData.value.forEach((row) => {
                  elTableRef.value.toggleRowSelection(row, true)
                })
              } else {
                selectData.value = []
              }
            }, 0)
          }
        }
      }
      watch(
        () => tableObject.currentPage,
        () => {
          Gou()
        },
        { immediate: true }
      )
    }
  }
)
// 盘点类型
let formInline: any = ref()
watch(
  () => ff.value.pasture_org_id,
  (a) => {
    if (a) {
      formInline.value = [
        {
          value: '1',
          label: '全部盘点'
        },
        {
          value: '2',
          label: '部分盘点'
        },
        {
          value: '3',
          label: '栏位盘点'
        },
        {
          value: '4',
          label: '贷款单盘点'
        },
        {
          value: '5',
          label: '保险单盘点'
        }
      ]
    }
  },
  { immediate: true }
)
//所属部门
let dept: any = ref([])
watch(
  () => ff.value.pasture_org_id,
  async (a, b) => {
    if (b !== '') {
      ff.value.pasture_dept_id = ''
      ff.value.pasture_dept_name = ''
      ff.value.type = ''
    }
    console.log(a, b)
    const data = await ucDeptListApi({ org_id: a })
    dept.value = data.data
  }
)
// prop值
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  },
  id: {
    type: String,
    default: null
  }
})
// console.log(props.detailSchema)

const checkedAll = ref(false)
const selectData = ref([])
const noSelectData = ref([])
// (修改) 调用查看接口获取信息
const getMedicalOrderSee = async () => {
  if (props.id) {
    const res = await zcInventoryRuleSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      ff.value = await res.data
      typeOne.value = ff.value.type
      dept.value = [{ dept_id: res.data.pasture_dept_id, dept_name: res.data.pasture_dept_name }]
      checkedAll.value = JSON.parse(res.data.select_json).checkedAll
      if (checkedAll.value) {
        const aaa = []
        JSON.parse(res.data.select_json).selected.forEach((element) => {
          let obj = {}
          obj.id = element
          aaa.push(obj)
        })
        noSelectData.value = aaa
      } else {
        const aaa = []
        JSON.parse(res.data.select_json).selected.forEach((element) => {
          let obj = {}
          obj.id = element
          aaa.push(obj)
        })
        selectData.value = aaa
      }
    }
    // await methods.setValues(ff.value)
  } else {
  }
}
const init = async () => {
  // 调用查看接口查询数据
  await getMedicalOrderSee()
  // 获取关联关系
  await getDictRels()
}
init()

// 栏位盘点选项
function currentChecked(nodeObj, SelectedObj) {
  console.log(SelectedObj.checkedKeys, nodeObj) // 这是选中的节点的key数组
  // console.log(SelectedObj.checkedNodes) // 这是选中的节点数组
  ff.value.selected = SelectedObj.checkedKeys
  // console.log(ff.value, '3333')
}
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 100,
    table: {
      show: true
    },
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'asset_code',
    label: '注射编号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code_2',
    label: '项圈编号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'earcon_code',
    label: '耳标编号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'pasture_org_name',
    label: '牧场',
    width: 150
  },
  {
    field: 'breed',
    label: '畜别',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    width: 80,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.breed,
        onChange: breedChange
      },
      show: false
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: breedSubData
      },
      show: false
    }
  },
  {
    field: 'sex',
    label: '性别',
    // width: 150,
    search: {
      show: false
    },
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('animal_sex', cellValue)
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 200,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
    // search: {
    //   show: true,
    //   component: 'DatePicker',
    //   componentProps: {
    //     'is-range': true,
    //     'unlink-panels': true,
    //     rangeSeparator: 'To',
    //     type: 'daterange',
    //     valueFormat: 'YYYY-MM-DD HH:mm:ss'
    //   }
    // }
  }
])
const { allSchemas } = useCrudSchemas(crudSchemas)

defineExpose({ ff, ruleFormRef, methodss })
</script>

<style lang="scss" scoped>
.el-form {
  display: flex;
  flex-wrap: wrap;
}
.el-form > div {
  width: 50%;
}
</style>
